package com.adjy.pathbuilders.screens;

import java.util.LinkedList;
import java.util.List;

import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.adjy.pathbuilders.R;
import com.adjy.pathbuilders.commons.FontLoader;
import com.adjy.pathbuilders.commons.FontLoader.Fonts;
import com.adjy.pathbuilders.objects.button.Button;
import com.adjy.pathbuilders.objects.button.ImageButton;
import com.adjy.pathbuilders.objects.button.TextImageButton;
import com.adjy.pathbuilders.objects.button.listeners.BackToMainMenuButtonListener;
import com.adjy.pathbuilders.objects.button.listeners.ButtonListener;
import com.adjy.pathbuilders.rendering.DisplayConverter;
import com.adjy.pathbuilders.rendering.GameCanvas;
import com.adjy.pathbuilders.rendering.loading.AnimationFactory;
import com.adjy.pathbuilders.rendering.loading.WeakReferenceBitmap;
import com.adjy.pathbuilders.screens.content.CustomDialog;
import com.adjy.pathbuilders.social.FacebookConnect;
import com.adjy.pathbuilders.state.Game;
import com.adjy.pathbuilders.world.GameWorld;

/**
 * GameWorld class holds all information of the World of our Game<br>
 * This includes, GameObjects, Character, Scenarios, Physics, etc
 */
public class FinishedLevelScreen implements GameScreen {

	private AnimationFactory animationFactory;
	private Game game;
	private GameWorld gameWorld;
	private List<Button> buttons;
	private Paint textPaint;
	private Paint strokePaint;
	
	private float mostCoins;
	private float bestTime;
	private TextImageButton recordButton;
	private boolean publish;
	private String action;
	private boolean isTimeRecord;
	private boolean isCoinRecord;

	public FinishedLevelScreen(Game game, GameWorld gameWorld, AnimationFactory anFactory) {
		this.animationFactory = anFactory;
		this.game = game;
		this.gameWorld = gameWorld;
		this.buttons = new LinkedList<Button>();
		mostCoins = gameWorld.getLevel().getMostCoins();
		bestTime = gameWorld.getLevel().getBestTime();
		createPaints();
	}
	
	private void createButtons() {
		this.recordButton = new TextImageButton(140, 370, 
				new ButtonListener() {
			
			@Override
			public void onButtonPressed() {
				FinishedLevelScreen th = FinishedLevelScreen.this;
				if(th.publish){
					View.OnClickListener confirmOnClickListener = new View.OnClickListener() {
			            public void onClick(View v) {
			            	CustomDialog dialog = CustomDialog.getInstance();
							FinishedLevelScreen.this.game.getFbConnect().actionListener(dialog.getInput());
			            	dialog.getDialog().dismiss();
			            }
			        };
			        CustomDialog.getInstance().createDialog("Share your progress!", "Say what you are feeling:", th.action, confirmOnClickListener , null);
				}
			}
		},
		new WeakReferenceBitmap(animationFactory, "selected"),
		new WeakReferenceBitmap(animationFactory, "unselected"), "F");
		
		
		if (buttons.size() == 0) {
			
			Button b = new ImageButton(240, 370,
					new BackToMainMenuButtonListener(game),
					new WeakReferenceBitmap(animationFactory, "menu_selected"),
					new WeakReferenceBitmap(animationFactory, "menu_unselected"));
			buttons.add(b);
			
			ButtonListener listener = new ButtonListener() {
				
				@Override
				public void onButtonPressed() {
					if (gameWorld.getLevel().getNext() != null) {
						game.startLevel(gameWorld.getLevel().getNext());
					} else {
						// Last Level
						Toast.makeText(game.getContext(), game.getContext().getString(R.string.congratulations_last_level),
								Toast.LENGTH_SHORT).show();
					}
				}
			};
			
			b = new ImageButton(480, 370,
					listener,
					new WeakReferenceBitmap(animationFactory, "next_selected"),
					new WeakReferenceBitmap(animationFactory, "next_unselected"));
			buttons.add(b);
		}
	}

	/**
	 * Creates the default paint, which can write simple messages in the screen.
	 */
	private void createPaints() {
		int textSize = FontLoader.getInstance().getFontSize();
		textPaint = new Paint();
		textPaint.setARGB(255, 255, 98, 61);
		textPaint.setAntiAlias(true);
		textPaint.setTextSize(textSize);
		textPaint.setTypeface(FontLoader.getInstance().getFont(Fonts.HOBO));

		strokePaint = new Paint();
		strokePaint.setARGB(255, 172, 51, 22);
		strokePaint.setAntiAlias(true);
		strokePaint.setStrokeWidth(3);
		strokePaint.setTextSize(textSize);
		strokePaint.setStyle(Style.STROKE);
		strokePaint.setTypeface(FontLoader.getInstance().getFont(Fonts.HOBO));
	}

	/**
	 * This method performs one step.<br>
	 * 
	 * @param timePassed
	 *            Elapsed Time in Seconds
	 */
	public void step(float timePassed) {
	}

	/**
	 * Method to receive any input events coming on the screen
	 * 
	 * @param event
	 *            Event from the screen
	 */
	public void input(MotionEvent event) {
		
		for (Button b : buttons)
			b.input(event);
		this.recordButton.input(event);
	}

	@Override
	public void load() {
		createButtons();
		this.animationFactory.loadImages("finished_level_bg", "selected", "unselected");
	}

	@Override
	public void release() {
		buttons.clear();
		this.recordButton = null;
		this.animationFactory.releaseImages("finished_level_bg", "selected", "unselected");
	}

	/**
	 * Renders the GameWorld
	 * 
	 * @param mcanvas
	 *            Canvas to be drawn on
	 */
	@Override
	public void render(GameCanvas mcanvas, float timeElapsed) {
		if (gameWorld.getMainChar() == null)
			return; // FIX this should never happen
		
		mcanvas.drawBackground(this.animationFactory.getImage("finished_level_bg")); // FIXME: this should be static)
		
		// FIXME: This Shouldn't be calculated every frame
		this.isTimeRecord = bestTime == -1 || bestTime > gameWorld.getCurrentTime();
		this.isCoinRecord = mostCoins < gameWorld.getMainChar().getPoints();
		
		String timeText = "Time: " + (int) gameWorld.getCurrentTime() + (isTimeRecord ? " (" + 
					game.getContext().getString(R.string.new_best) + ")": "");
		String coinText = "Coins: " + gameWorld.getMainChar().getPoints() + (isCoinRecord ? " (" + 
				game.getContext().getString(R.string.new_best) + ")": "");
		
		
		Point timePos = new Point((int) (DisplayConverter.getDisplaySize().getX() / 2 - textPaint.measureText(timeText) / 2),
				(int) (240 * DisplayConverter.getScreenRatioHeight()));
		
		Point coinPos = new Point((int) (DisplayConverter.getDisplaySize().getX() / 2 - textPaint.measureText(coinText) / 2),
				(int) (330 * DisplayConverter.getScreenRatioHeight()));
		
		mcanvas.drawText(timeText, timePos.x, timePos.y, textPaint);
		mcanvas.drawText(timeText, timePos.x, timePos.y, strokePaint);

		mcanvas.drawText(coinText, coinPos.x, coinPos.y, textPaint);
		mcanvas.drawText(coinText, coinPos.x, coinPos.y, strokePaint);
		
		for(Button b : buttons)
			b.render(mcanvas, timeElapsed);
		
		getMsg();
		if(this.publish) this.recordButton.render(mcanvas, timeElapsed);
	}

	public void resetTimer() {
	}

	public void actionListener(String action) {
		this.publish = FacebookConnect.getInstance().isLoggedOnFacebook() && action != null && !action.isEmpty();
		this.action = action;
	}
	
	private String getMsg() {
		String action = "";
		if(this.isCoinRecord) {
			action = ("[" /*+ level.getLevelID()*/ + "] I got the best ranking on PathBuilders!\n");
		} else if(this.isTimeRecord) {
			action += ("[" /*+ level.getLevelID()*/ + "] I got the best time on PathBuilders!");
		}
		actionListener(action);
		return action;
	}
}
